/*
 * $Id$
 */
package corejs.util;

import corejs.stmt.Statement;
import corejs.expr.Expression;

import static java.lang.String.format;
import java.util.Stack;

/**
 *
 * @author myang
 */
public class XmlPrinter {
   
   private int _indent = 0;
   private StringBuilder _buffer = new StringBuilder();
   private Stack<String> _tags = new Stack<String>();

   public XmlPrinter incIndent() {
      _indent += 4;
      return this;
   }

   public XmlPrinter descIndent() {
      _indent -= 4;
      return this;
   }

   public XmlPrinter open(final String tag) {
      _tags.push(tag);
      indent().append(format("<%s>%n", tag));
      return this.incIndent();
   }

   public XmlPrinter close() {
      descIndent().indent().append(format("</%s>%n", _tags.pop()));
      return this;
   }

   public XmlPrinter print(final String tag) {
      indent().append(format("<%s />%n", tag));
      return this;
   }

   public XmlPrinter print(final String tag, final String... text) {
      if (text.length == 0) {
         return print(tag);
      }

      final StringBuilder sb = new StringBuilder();
      int i = 0;
      for (;i < text.length - 1; ++i) {
         sb.append(text[i]).append(",");
      }
      if (i < text.length) {
         sb.append(text[i]);
      }
      return print(tag, sb.toString());
   }

   public XmlPrinter print(final String tag, final String text) {
      indent().append(format("<%s>%s</%s>%n", tag, text, tag));
      return this;
   }

   public XmlPrinter print(final Expression expr) {
      expr.print(this);
      return this;
   }

   public XmlPrinter print(final Statement stmt) {
      stmt.print(this);
      return this;
   }

   public StringBuilder indent() {
      for (int i = 0; i < _indent; ++i) {
         _buffer.append(' ');
      }
      return _buffer;
   }

   public void print() {
      System.out.println(_buffer.toString());
   }
}
